#include "main.h"

void copyArc (FILE * arc[],fileHead * list[])
{
	int m = 0;
	int rc = 0;
	char * buf = (char *) calloc (SIZE_BUF,sizeof(char));
	unsigned int ChkSum = 0;
	unsigned int ChkSum_orig = 0;
	unsigned long long int sizeFileSz = 0;
	if (!buf)	cl_exit (COPY_ARC, MEMORY_ERR);
	fseek (arc[0],0,SEEK_SET);
	fseek (arc[1],0,SEEK_SET);
	rc = fread (buf,sizeof(char),SIGN_LEN,arc[0]);	
	envInf.buf = buf;
	if (rc != SIGN_LEN)	{	cl_exit (COPY_ARC, READ_ERR);	}
	rc = fwrite (buf,sizeof(char),SIGN_LEN,arc[1]);
	if (rc != 7)	{	cl_exit (COPY_ARC,WRITE_ERR);	}
	while(list[m])
	{
		ChkSum = 0;	if ((list[m]->rplFlag & DEL_FILE_FL) || (list[m]->rplFlag & REPL_FILE))	{
			spaceJump (arc[0],list[m]);
		} 
		else {
			intWrite (arc[1],(unsigned long long int)list[m]->sizeName,NAME_LEN,&ChkSum);
			strWrite (arc[1],list[m]->fileName,list[m]->sizeName,&ChkSum);
			intWrite (arc[1],(unsigned long long int)list[m]->mtime,SIZE_T_8,&ChkSum);
			intWrite (arc[1],(unsigned long long int)list[m]->huff_ubits,SIZE_T_1,&ChkSum);	
			fseek (arc[0],list[m]->sizeName + 10,SEEK_CUR);
			if (list[m]->huff_ubits & LEN_8_B)	{
				intWrite (arc[1],(unsigned long long int)list[m]->fileSize,SIZE_T_8,&ChkSum);
				fseek (arc[0],SIZE_T_8,SEEK_CUR);
				sizeFileSz = SIZE_T_8;
			} 
			else {
				intWrite (arc[1],(unsigned long long int)list[m]->fileSize,SIZE_T_4,&ChkSum);
				fseek (arc[0],SIZE_T_4,SEEK_CUR);
				sizeFileSz = SIZE_T_4;
			}
			if (!(list[m]->huff_ubits & NO_HUFF))	{
				intWrite (arc[1],(unsigned long long int)list[m]->huff_block,SIZE_T_2,&ChkSum);
				intWrite (arc[1],(unsigned long long int)list[m]->huff_file_len,sizeFileSz,&ChkSum);	
				fseek (arc[0],SIZE_T_2 + sizeFileSz,SEEK_CUR);
				sizeFileSz = list[m]->huff_file_len;
			} 
			else {
				sizeFileSz = list[m]->fileSize;
			}
			if ((rc = copy (arc[0],arc[1],sizeFileSz,&ChkSum)) != 0)	{	
				cl_exit (COPY_ARC,COPY_ERR);	
			}
#ifdef __DEBUG_
		printf ("old 2 %u" ,  ChkSum);
#endif
			if ((rc = fread (buf,sizeof(char),SIZE_T_4,arc[0])) != SIZE_T_4)	{
				envInf.buf = buf; 
				cl_exit (COPY_ARC, READ_ERR);
			}
			ChkSum_orig = strToInt (buf, SIZE_T_4);
			if (ChkSum_orig != ChkSum) {	cl_exit (COPY_ARC, CS_ERR);	} 
			else {
				intWrite (arc[1],(unsigned long long int)ChkSum,SIZE_T_4,&ChkSum);
			}
		}
		m++;
	}
}